import java.util.Arrays;
import java.util.Random;

public class SelectSort {
    /*
     * 稳定性： 不稳定 见附图
     * 时间复杂度：O(N^2) 》》 外层循环 n -1，内层循环 n -1
     * 空间复杂度：O(1)
     * */

    // 优化
    public static void selectSort(int[] array){
        for (int i = 0; i < array.length-1; i++) {
            int index = i;
            for (int j = i + 1; j < array.length; j++) {
                if(array[index] > array[j]){
                    index = j;
                }
            }
            int tmp = array[i];
            array[i] = array[index];
            array[index] = tmp;
        }
    }

    // 未优化
//    public static void selectSort(int[] array){
//        for (int i = 0; i < array.length-1; i++) {
//            for (int j = i + 1; j < array.length; j++) {
//                if(array[i] > array[j]){
//                    int tmp = array[i];
//                    array[i] = array[j];
//                    array[j] = tmp;
//                }
//            }
//        }
//    }

    // 有序
    public static void test1(int capacity){
        int[] array = new int[capacity];
        for (int i = 0; i < capacity; i++) {
            array[i] = i;
        }
        long start = System.currentTimeMillis();
        selectSort(array);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    // 无序
    public static void test2(int capacity){
        int[] array = new int[capacity];
        Random random = new Random();
        for (int i = 0; i < capacity; i++) {
            array[i] = random.nextInt(capacity);
        }
        long start = System.currentTimeMillis();
        selectSort(array);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }


    public static void main(String[] args) {
        test1(10000);
        test2(10000);
//        int[] array = {12,5,3,7,1};
//        selectSort(array);
//        System.out.println(Arrays.toString(array));
    }
}
